//
//  AppDelegate.m
//  AmazingShopping
//
//  Created by Tan on 4/6/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "AppDelegate.h"

BOOL isLogin = NO;
BOOL isFromHome = NO;
NSString *seperatorString = @"|";

@implementation AppDelegate

@synthesize rootController, serverPath, userInfoPath;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [[NSBundle mainBundle]loadNibNamed:@"TabBarController" owner:self options:nil];
    [self.window setRootViewController:rootController];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    serverPath = [self serverPath];
    
    //Add notification listenrs
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCart:) name:@"ChangedUserStatus" object:nil];
    
    //Add notification listenrs to Cart Tabbar
    [[NSNotificationCenter defaultCenter] addObserver:[[[rootController.viewControllers objectAtIndex:2] viewControllers] objectAtIndex:0] selector:@selector(getProductData:) name:@"AddedProductInCart" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:[[[rootController.viewControllers objectAtIndex:2] viewControllers] objectAtIndex:0] selector:@selector(getProductData:) name:@"ChangedUserStatus" object:nil];
    
    [self setUserStatus];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    NSLog(@"ResignActive");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    //Check Internet Connection Here
    NSURL *url = [NSURL URLWithString:serverPath];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)updateCart:(NSNotification *)noti{
//    NSMutableDictionary *userData = [[NSMutableDictionary alloc]initWithContentsOfFile:userInfoPath];
//    productInCart = [[NSMutableDictionary alloc]initWithDictionary:[userData valueForKey:@"ProductInCart"]];
//    if (isLogin) {        
//        //Get product in cart of user
//        NSString *url = [NSString stringWithFormat:@"%@/get_cart", serverPath];
//        ASIFormDataRequest *request = [[ASIFormDataRequest alloc]init];
//        [request setURL:[NSURL URLWithString:url]];
//        NSString *path = [self userInfoPath];
//        NSMutableDictionary *userData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//        NSString *userID = [userData objectForKey:@"ID"];
//        [request addPostValue:userID forKey:@"userID"];
//        [request setDelegate:self];
//        [request setTag:0];
//        [request startAsynchronous];
//    }else{
//        if (productInCart.count > 0) {
//            NSArray *qtyArray = [productInCart allValues];
//            int qty = 0;
//            for (int i = 0; i < qtyArray.count; i++) {
//                qty += [[qtyArray objectAtIndex:i] integerValue];
//            }
//            [[[rootController.tabBar items] objectAtIndex:2] setBadgeValue:[NSString stringWithFormat:@"%d", qty]];
//        }else{
//            [[[rootController.tabBar items] objectAtIndex:2] setBadgeValue:nil];
//        }
//    }
}

- (void)setUserStatus{
    NSString *path = [self userInfoPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath: path]){
    }else{
        NSMutableDictionary *userData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
        
        //Check user login status
        NSString *value = [userData objectForKey:@"IsLogin"];
        if ([value isEqualToString:@"YES"]) {
            isLogin = YES;
        }else{
            isLogin = NO;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangedUserStatus" object:self];
    }
}

- (NSString *)serverPath{
    if (serverPath == nil) {
//        serverPath = @"http://192.168.1.38/amazingshoppingserver/index.php/api/";
        serverPath = @"http://local.amazing.vn/api/";
    }
    return serverPath;
}

- (NSString *)userInfoPath{
    if (userInfoPath == nil) {
        userInfoPath = [[NSBundle mainBundle]pathForResource:@"UserInfo" ofType:@"plist"];
    }
    return userInfoPath;
}

#pragma mark ASIHTTPRequest Delegates

- (void)requestFailed:(ASIHTTPRequest *)request{
    
//    switch ([request tag]) {
//        case 0:{    ////Request to get products in cart
//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Sorry, we can't get products information in your cart" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
//            [alertView show];
//        }
//            break;
//            
//        default:
//            break;
//    }
}

- (void)requestFinished:(ASIHTTPRequest *)request{
//    switch ([request tag]) {
//        case 0:{    //Request to get products in cart
////            NSData *responseData = [request responseData];
////            JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
////            NSArray *temp = [jsonDecoder objectWithData:responseData];
////            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"asdasd" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
////            [alertView show];
//        }
//            break;
//            
//        default:
//            break;
//    }
}

@end
